package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.utils.JSONUtil;
import net.suncaper.psychological.common.utils.Result;
import net.suncaper.psychological.model.domain.CaseReport;
import net.suncaper.psychological.service.ICaseReportService;
import net.suncaper.psychological.service.impl.CaseReportServiceImpl;
import net.suncaper.psychological.utils.WordExportUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import com.alibaba.fastjson.JSON;

@WebServlet("/api/case-report/*")
public class CaseReportController extends HttpServlet {
    
    private final ICaseReportService caseReportService = new CaseReportServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        try {
            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有结案报告
                List<CaseReport> caseReports = caseReportService.getAllCaseReports();
                JSONUtil.writeJSON(response, Result.success(caseReports));
            } else if (pathInfo.startsWith("/appointment/")) {
                // 根据预约ID查询
                Long appointmentId = Long.parseLong(pathInfo.substring(12));
                CaseReport caseReport = caseReportService.getCaseReportByAppointmentId(appointmentId);
                JSONUtil.writeJSON(response, Result.success(caseReport));
            } else if (pathInfo.startsWith("/student/")) {
                // 根据学生ID查询
                Long studentId = Long.parseLong(pathInfo.substring(9));
                List<CaseReport> caseReports = caseReportService.getCaseReportsByStudentId(studentId);
                JSONUtil.writeJSON(response, Result.success(caseReports));
            } else if (pathInfo.startsWith("/consultant/")) {
                // 根据咨询师ID查询
                Long consultantId = Long.parseLong(pathInfo.substring(12));
                List<CaseReport> caseReports = caseReportService.getCaseReportsByConsultantId(consultantId);
                JSONUtil.writeJSON(response, Result.success(caseReports));
            } else {
                JSONUtil.writeJSON(response, Result.error("无效的请求路径"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.writeJSON(response, Result.error("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.writeJSON(response, Result.error("查询失败: " + e.getMessage()));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 创建结案报告
            String requestBody = JSONUtil.getRequestBody(request);
            System.out.println("接收到的请求数据: " + requestBody);
            
            CaseReport caseReport = JSON.parseObject(requestBody, CaseReport.class);
            
            if (caseReport == null) {
                System.out.println("解析CaseReport对象失败");
                JSONUtil.writeJSON(response, Result.error("请求数据格式错误"));
                return;
            }
            
            System.out.println("解析后的CaseReport对象: " + JSON.toJSONString(caseReport));
            
            boolean success = caseReportService.createCaseReport(caseReport);
            System.out.println("创建结案报告结果: " + success);
            
            if (success) {
                // 创建成功后，生成Word文档并返回
                try {
                    System.out.println("开始生成Word文档...");
                    byte[] wordBytes = WordExportUtil.generateCaseReportWord(caseReport);
                    System.out.println("Word文档生成成功，大小: " + wordBytes.length + " bytes");
                    
                    // 设置响应头
                    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                    response.setHeader("Content-Disposition", "attachment; filename=\"结案报告_" + 
                        (caseReport.getName() != null ? caseReport.getName() : "未知") + ".docx\"");
                    response.setContentLength(wordBytes.length);
                    
                    // 写入Word文档
                    response.getOutputStream().write(wordBytes);
                    response.getOutputStream().flush();
                    System.out.println("Word文档已写入响应流");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("Word文档生成失败: " + e.getMessage());
                    // 如果Word生成失败，仍然返回成功，但不提供下载
                    JSONUtil.writeJSON(response, Result.success("结案报告创建成功，但Word文档生成失败"));
                }
            } else {
                System.out.println("结案报告创建失败");
                JSONUtil.writeJSON(response, Result.error("结案报告创建失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("处理请求时发生异常: " + e.getMessage());
            JSONUtil.writeJSON(response, Result.error("创建失败: " + e.getMessage()));
        }
    }
    
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 更新结案报告
            String requestBody = JSONUtil.getRequestBody(request);
            CaseReport caseReport = JSON.parseObject(requestBody, CaseReport.class);
            
            if (caseReport == null || caseReport.getId() == null) {
                JSONUtil.writeJSON(response, Result.error("请求数据格式错误或缺少ID"));
                return;
            }
            
            boolean success = caseReportService.updateCaseReport(caseReport);
            if (success) {
                JSONUtil.writeJSON(response, Result.success("结案报告更新成功"));
            } else {
                JSONUtil.writeJSON(response, Result.error("结案报告更新失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.writeJSON(response, Result.error("更新失败: " + e.getMessage()));
        }
    }
    
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        try {
            if (pathInfo != null && pathInfo.startsWith("/")) {
                Long id = Long.parseLong(pathInfo.substring(1));
                boolean success = caseReportService.deleteCaseReport(id);
                if (success) {
                    JSONUtil.writeJSON(response, Result.success("结案报告删除成功"));
                } else {
                    JSONUtil.writeJSON(response, Result.error("结案报告删除失败"));
                }
            } else {
                JSONUtil.writeJSON(response, Result.error("缺少删除ID"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.writeJSON(response, Result.error("ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.writeJSON(response, Result.error("删除失败: " + e.getMessage()));
        }
    }
} 